package com.zt.interceptor;

import com.zt.utils.CurrentHolder;
import com.zt.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取token
        String token = request.getHeader("Token");
        //判断token是否为空
        if (token == null || token.equals("")) {
            //抛出异常
            //设置状态码为401并返回
            response.setStatus(401);
            return false;
        }
        //解析token
        try {
            Claims claims = JwtUtils.parseJWT(token);
            //获取用户id
            Integer id = claims.get("id", Integer.class);
            //将用户id存入ThreadLocal
            CurrentHolder.setCurrentId(id);
        } catch (Exception e) {
            response.setStatus(401);
            return false;
        }
        //放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        CurrentHolder.removeId();
    }
}
